﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;

namespace WorkSchedueSoft.Data
{
    class DataManager : Singleton<DataManager>
    {

        const string data_file_name = "save.json";

        private List<SchedueItem> _schedue_items;
        private Dictionary<string, SchedueItem> _dict_schedue_items;
        private SchedueItem current_schedueitem;
        private SchedueCommandItem current_command_item;

        internal List<SchedueItem> Schedue_items
        {
            get
            {
                return _schedue_items;
            }
        }

        internal Dictionary<string, SchedueItem> Dict_schedue_items
        {
            get
            {
                return _dict_schedue_items;
            }
        }

        internal SchedueItem Current_schedueitem
        {
            get
            {
                return current_schedueitem;
            }

            set
            {
                current_schedueitem = value;
            }
        }

        public SchedueCommandItem Current_command_item
        {
            get
            {
                return current_command_item;
            }

            set
            {
                current_command_item = value;
            }
        }

        public override void Init()
        {
            base.Init();

            _schedue_items = new List<SchedueItem>();
            _dict_schedue_items = new Dictionary<string, Data.SchedueItem>();
            LoadData();
            RefreshData();

        }

        public void RefreshData()
        {
            if (_schedue_items.Count > 0)
            {
                _dict_schedue_items.Clear();
                foreach (var item in _schedue_items)
                {
                    _dict_schedue_items.Add(item.name, item);
                }
            }
        }

        public void LoadData()
        {
            if (File.Exists(data_file_name))
            {
                string jsstr = File.ReadAllText(data_file_name);
                SaveData dat = JsonConvert.DeserializeObject<SaveData>(jsstr);
                this._schedue_items = dat.schedueItem;
            }
        }

        public void SaveData()
        {
            SaveData dat = new Data.SaveData();
            dat.schedueItem = this._schedue_items;
            string jsstr = JsonConvert.SerializeObject(dat,Formatting.Indented);
            File.WriteAllText(data_file_name, jsstr);
        }

    }
}
